< previous page page_624 next page >

Page 624
If you write a function TraceRay to follow a ray and return the color at the point of its first intersection, you can describe the recursive ray tracing algorithm like this.
1. Find ray M in the reflection direction.
2. TraceRay = Local components (ambient, diffuse, specular) + kr * TraceRay(M).
Here, kr is a constant that represents the reflectiveness of the surface. If the surface is very reflective, kr should be close to one. If the surface is not very reflective, kr should be close to zero.
Adding this term to the lighting model gives:
e10a6a0a59f035e870d90cca05b85fce.gif
I  = Ia * ka + 
     I
i * (kd * (L  N) + ks * (R . V)n) *
         (r
min + kdist) / (r + kdist) +
     I
r * kr
In this equation, Ir is the reflected component computed recursively.
The TraceRay function takes parameters that indicate the starting point and direction of a ray. It returns through parameters the red, green, and blue color components of the pixel where the ray intersects an object.
Once it has found the point of intersection between the ray and an object, TraceRay calls the object's FindHitColor routine to calculate the pixel's color. FindHitColor does little more than calculate the object's surface normal and then invoke the CalculateHitColor subroutine. This is the subroutine that contains the color model information and that does all the interesting work.
The following code fragment shows the part of CalculateHitColor that deals with reflected light. You can see the complete source code on the CD-ROM, and you can learn more about the other parts of the shading model in Chapter 16, Shading Models.
When CalculateHitColor examines a reflective surface, it finds the mirror direction for the ray it is following. It then calls subroutine TraceRay to follow a new ray in that direction to find the reflected light's contribution. TraceRay calls FindHitColor, which calls CalculateHitColor, and the recursion starts all over again.
The depth parameter controls the depth of recursion. Each time CalculateHitColor calls TraceRay, it decreases depth. That guarantees that the recursion eventually stops when depth is zero.
e10a6a0a59f035e870d90cca05b85fce.gif
' Return the red, green, and blue components of
' an object at a hit position (px, py, pz) with
' normal vector (nx, ny, nz)
Public Sub CalculateHitColor(ByVal depth As Integer, _
    Objects As Collection, . . .)
        :
    ' *************
    ' * Reflected *
    ' *************

 
< previous page page_624 next page >